<?php

require_once 'Pipes/FileSystem/ModelList/Finder.php';
require_once 'Pipes/FileSystem/ModelList/Loader.php';
require_once 'Pipes/Filter.php';
require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Model/Meta.php';

class PipesCore_Models_Finders_All
{
	private $_config = null;
	private $_loader = null;
	private $_meta = null;

	public function __construct(PipesImpl_Config $config, PipesImpl_Model_Meta $meta) {
		$this->_config = $config;
		$this->_loader = new Pipes_FileSystem_ModelList_Loader(
			new Pipes_FileSystem_ModelList_Finder($config)
		);
		$this->_meta = $meta;
	}

	public function find($criteria = null) {
		if ($criteria instanceof PipesImpl_Filter) {
			$substitutions = $criteria->getSubstitutions();
			$conditions = $criteria->getCondition();
		} else {
			$substitutions = array();
			$conditions = 1;
		}

		$query = "
			SELECT
				`{$this->_meta->getName()}s`.*
			FROM
				`{$this->_meta->getName()}s`
			WHERE
				{$conditions}";
		$statement = $this->_config->pdo->prepare($query);
		$statement->execute($substitutions);
		
		$result = $statement->fetchAll(PDO::FETCH_ASSOC);
		$statement->closeCursor();

		$exploded = explode('_', $this->_meta->getModelName());
		$this->_loader->load(array_pop($exploded));
		$listName = $this->_loader->lastLoaded;

		return new $listName($this->_config, $this->_meta, $result);
	}
}
